// pages/look/index.js
const app = getApp()
Page({

     /**
      * 页面的初始数据
      */
     data: {
          userInfo: {},
          current: 0,
          reward_pay: false, //打赏支付弹窗开启
          type: 0,
          data: {},
          reward_type: 'single', //打赏类型
          pay_type: 'mag',
          imgTop: [-1, -1, -1, -1, -1, -1, -1, -1, -1], //轮播图每个图片距离顶部的高度，为了计算右上角图标位置
          is_myself: false, //当前图集是不是自己发的 ...
          is_footer: true,
          mag_balance: 0,
          is_wxpay: 0,
          setting: {},
          paying: false,
          isAuthorize:true
     },

     /**
      * 生命周期函数--监听页面加载
      */
     onLoad: function (options) {

          let that = this;
          //是否开启微信支付
          app.connect('index/setting', {}, function (res) {
               that.setData({
                    is_wxpay: res.is_wxpay,
                    setting: res
               })
          });

          var content_id = options.content_id;
          var img_id = options.img_id;
          if (options.type != undefined) {
               that.setData({
                    type: options.type
               });
          }
          //判断有没有授权登录
          wx.getSetting({
               success(res) {
                    //没有授权
                    if (!res.authSetting['scope.userInfo']) {
                         that.setData({
                              isAuthorize: false
                         });

                    } else {
                         that.setData({
                              isAuthorize: true
                         });
                    }
               }
          })
         
          app.login_canno(function (userInfo) {
          if (userInfo != null) {
               that.setData({
                    userInfo: userInfo.data
               });
          }

          if (that.data.userInfo.uid != undefined && that.data.userInfo.openId != undefined) {
               var data = {
                    content_id: content_id,
                    uid: that.data.userInfo.uid,
                    openid: that.data.userInfo.openId
               };
          } else {
               var data = {
                    content_id: content_id
               };
          }
          //加载数据
          app.connect('content/detail', data, function (options) {
               console.log(options);
               //点轮播图X位照片时，直接打开至X位照片
               for (var x in options.imgs) {
                    if (options.imgs[x].id == img_id) {
                         that.setData({
                              current: parseInt(x)
                         });
                    }
               }
               if (options.uid == that.data.userInfo.uid) {
                    that.setData({
                         is_myself: true
                    })
               }
               //计算打赏照片价格
               options.rmb_reward_all = options.rmb_reward_single * that.reward_count(options.imgs);
               options.mag_reward_all = options.mag_reward_single * that.reward_count(options.imgs);

               //解锁全部
               if (that.data.type == 2 && options.mag_reward_all > 0 && that.data.userInfo.uid != options.uid) {
                    app.login(function (userInfo) {

                         that.setData({
                              userInfo: userInfo.data
                         });
                    })
                    that.setData({
                         reward_pay: true,
                         reward_type: 'all'
                    });
               }
               that.setData({
                    data: options
               });


               //加载麦粒余额
               if (app.isPoneAvailable(that.data.userInfo.mobile)) { //手机号已绑定
                    app.connect('account/getMagBalance', {
                         uid: that.data.userInfo.uid,
                         openid: that.data.userInfo.openId,
                         mobile: that.data.userInfo.mobile
                    }, function (res) {
                         console.log(res);
                         var balance = res.data == null ? 0 : res.data.balance;
                         that.setData({
                              mag_balance: parseFloat(balance).toFixed(2)
                         });
                    });
               }
          }, true);
     })

},

     /**
      * 用户点击右上角分享
      */
     onShareAppMessage: function () {

     },
     /**
      * 图片翻页
      */
     changeImg: function (e) {
          var current = e.detail.current;
          this.setData({
               current: current
          });
     },
     //点击打赏
     reward: function (e) {
          let that = this;
          app.login(function (userInfo) {

               that.setData({
                    userInfo: userInfo.data
               });

               //加载麦粒余额
               if (app.isPoneAvailable(that.data.userInfo.mobile)) { //手机号已绑定
                    app.connect('account/getMagBalance', {
                         uid: that.data.userInfo.uid,
                         openid: that.data.userInfo.openId,
                         mobile: that.data.userInfo.mobile
                    }, function (res) {
                         var balance = res.data == null ? 0 : res.data.balance;
                         that.setData({
                              mag_balance: parseFloat(balance).toFixed(2)
                         });
                    });
               }
          })
          if (this.data.reward_pay == false) {
               this.setData({
                    reward_pay: true
               });
          }
     },
     //关闭打赏支付弹窗
     close: function () {
          this.setData({
               reward_pay: false
          });
     },
     /**
      * 预览图片
      */
     yulan: function (e) {

          var pic_path = e.currentTarget.dataset.src;
          var data = this.data.data.imgs;
          var urls = [];
          for (var x in data) {
               if (data[x].type == 1 || data[x].is_reward == 1) {
                    urls.push(data[x].pic_path);
               }
          }
          wx.previewImage({
               current: pic_path, // 当前显示图片的http链接
               urls: urls // 需要预览的图片http链接列表
          })
     },
     /**
      * 切换支付类型
      */
     changePayType: function () {
          let that = this;
          var pay_type = that.data.pay_type == 'mag' ? 'rmb' : 'mag';
          that.setData({
               pay_type: pay_type
          })
     },
     /**
      * 切换解锁类型
      */
     changeRewardType: function (e) {
          let that = this;
          var reward_type = that.data.reward_type == 'single' ? 'all' : 'single';
          that.setData({
               reward_type: reward_type
          })
     },
     /**
      * 点击支付
      */
     pay: function (e) {
          let that = this;
          that.setData({
               reward_pay: false
          });
          app.login(function (userInfo) {

               that.setData({
                    userInfo: userInfo.data
               });
               let current = that.data.current;
               let imgs_id = that.data.data.imgs[current].id; //图id
               let money = that.data.reward_type == 'single' ? that.data.data[that.data.pay_type + "_reward_single"] : that.data.data[that.data.pay_type + "_reward_all"]; //支付金额
               let content_id = that.data.data.id; //内容id
               let uid = that.data.userInfo.uid;
               let type = that.data.pay_type == 'rmb' ? 1 : 2; //支付类型
               let reward_type = that.data.reward_type;
               if (that.data.pay_type == 'rmb') {
                    //人民币支付
                    //首先生成订单
                    app.connect('reward/setOrder', {
                         openid: that.data.userInfo.openId,
                         content_id: content_id,
                         uid: uid,
                         money: money,
                         type: type,
                         imgs_id,
                         imgs_id,
                         reward_type: reward_type
                    }, function (res) {
                         //订单短期内只能提交一次，避免同时产生多笔订单

                         var order_id = res.order_id;
                         //发起微信支付
                         app.connect('wxpay/wxpay', {
                              money: money,
                              openid: that.data.userInfo.openId,
                              order_id: order_id
                         }, function (e) {
                              console.log(e);
                              //小程序唤起支付
                              var prepay_id = e.prepay_id;
                              wx.requestPayment({
                                   timeStamp: e.timeStamp, //时间
                                   nonceStr: e.nonce_str, //随机字符创
                                   package: "prepay_id=" + e.prepay_id,
                                   signType: "MD5",
                                   paySign: e.sign,
                                   success: function (e) {
                                        //成功后处理
                                        app.connect('wxpay/paySuccess', {
                                             order_id: order_id
                                        }, function (e) {

                                             if (e.msg == 'success') {
                                                  wx.showToast({
                                                       title: '解锁成功',
                                                       icon: 'none'
                                                  })
                                                  that.setData({
                                                       reward_pay: false
                                                  });
                                                  that.onLoad({
                                                       content_id: content_id
                                                  })
                                             }
                                        });
                                   },
                                   fail: function (e) {
                                        console.log(e);
                                        //app.getUserInfo();
                                        // that.onLoad();
                                   }
                              });
                         })
                    });
               } else if (that.data.pay_type == 'mag') {
                    //mag 支付

                    //余额不足

                    if (that.data.mag_balance < parseFloat(money)) {

                         wx.showModal({
                              title: '余额不足，请先充值',

                              success: function (res) {
                                   if (res.confirm) {
                                        console.log(that.data.userInfo.mobile);
                                        if (!app.isPoneAvailable(that.data.userInfo.mobile)) {
                                             if (that.data.userInfo.invi_uid == '') {
                                                  wx.navigateTo({
                                                       url: '../login/index',
                                                  })
                                             } else {
                                                  wx.navigateTo({
                                                       url: '../inviation/login?invi_uid=' + that.data.userInfo.invi_uid,
                                                  })
                                             }

                                        } else {
                                             wx.navigateTo({
                                                  url: '../account/recharge',
                                             })
                                        }

                                   } else if (res.cancel) {
                                        that.close();
                                   }
                              }
                         })


                         return false;
                    } else {
                         //生成订单
                         app.connect('reward/setOrder', {
                              openid: that.data.userInfo.openId,
                              content_id: content_id,
                              uid: uid,
                              money: money,
                              type: type,
                              imgs_id,
                              imgs_id,
                              reward_type: reward_type
                         }, function (res) {
                              var order_id = res.order_id;
                              //发起麦粒转转账操作 
                              app.connect('account/magPay', {
                                   money: money,
                                   openid: that.data.userInfo.openId,
                                   uid: that.data.userInfo.uid,
                                   order_id: order_id
                              }, function (res) {
                                   console.log(order_id);
                                   console.log(res);
                                   if (res.code == 1) {
                                        console.log('成功');

                                        wx.showToast({
                                             title: res.msg,
                                             icon: 'none'
                                        })

                                   } else {
                                        wx.showToast({
                                             title: res.msg,
                                             icon: 'none'
                                        })

                                   }

                                   setTimeout(function () {
                                        that.onLoad({
                                             content_id: content_id
                                        })
                                   }, 1500)

                              })
                         })
                    }
               }
          })
     },
     /**
      * 应该打赏 图片个数
      */
     reward_count: function (imgs) {
          var count = 0;
          for (var x in imgs) {
               if (imgs[x].is_reward != 1 && imgs[x].type == 2) {
                    count++;
               }
          }
          return count;
     },
     imgLoad: function (e) {
          let that = this;
          var width = e.detail.width;
          var index = e.currentTarget.dataset.index;
          var height = e.detail.height;

          wx.getSystemInfo({
               success: function (res) {
                    //屏幕宽度与高度
                    var windowWidth = res.windowWidth;
                    var windowHeight = res.windowHeight;

                    //长图情况下
                    if ((height / width) >= (windowHeight / windowWidth)) {
                         var imgTop = 0;
                    } else {
                         var imgHeight = windowWidth * (height / width);
                         var imgTop = (windowHeight - imgHeight) / 2;
                    }
                    var oldImgTop = that.data.imgTop;
                    oldImgTop[index] = imgTop;
                    that.setData({
                         imgTop: oldImgTop
                    })

               }
          })
     },
     setFooter: function () {
          var is_footer = this.data.is_footer ? false : true;
          this.setData({
               is_footer: is_footer
          });
     },
     onShareAppMessage: function (res) {
          let that = this;

          return {
               title: '@' + that.data.data.nick + ' 在麦颜值发表的作品',
               imageUrl: that.data.data.imgs.pic_path
          }
     },
     getuserinfo: function (options) {
          let that = this;
       
          wx.getSetting({
               success(res) {
                    //授权
                    if (res.authSetting['scope.userInfo']) {

                         that.setData({
                              isAuthorize: true
                         });
                         app.getUserInfo(function (userInfo) {
                              //更新数据
                              that.setData({
                                   userInfo: userInfo.data
                              })
                              that.reward();
                         })
                    }else{
                         wx.showToast({
                              title:'授权登录才可以进行下一步操作~',
                              icon:'none'
                         })
                    }
               }
          })

     },
})